/*
 * @Author: fisher
 * @Date: 2024-02-21 23:47:05
 * @LastEditors: luthor luthor-li@qq.com
 * @LastEditTime: 2024-03-09 00:22:36
 * @FilePath: \allback\controllers\uploadController.js
 * @Description:
 */
// controllers/uploadController.js
const uploadService = require('../services/uploadService')
// const fs = require('fs-extra')
// const path = require('path')
const { generateId } = require('../utils/common')
// 存储合并任务的状态
const mergeStatus = new Map()
const uploadController = {
  async uploadFile(ctx) {
    try {
      const file = ctx.request.files.file // `file` 应该与前端上传字段名称相匹配
      // 获取存储在临时目录中的文件信息
      const fileData = {
        originalFilename: file.originalFilename,
        mimetype: file.mimetype,
        path: file.filepath,
        size: file.size
      }
      const savedFile = await uploadService.saveUploadFile(fileData)
      ctx.body = { message: '上传成功', status: true, data: savedFile }
    } catch (error) {
      throw new HttpError(error.message, 400)
    }
  },
  async uploadBigFile(ctx) {
    // console.log('files', ctx.request.files)
    const files = ctx.request.files.file // 获取上传的文件
    const { name, chunk, chunks } = ctx.request.body // 获取其他字段信息，比如原始文件名，当前分片和总分片数
    // console.log('name, chunk, chunks', name, chunk, chunks)
    // 以下代码视你的应用逻辑而定，你可能需要更复杂的文件检查和错误处理机制
    if (!files || !name || !chunk || !chunks) {
      ctx.status = 400
      ctx.body = { status: false, message: '参数不正确' }
      return
    }
    try {
      // 以下代码仅示例，你需要根据实际业务需求来处理分片
      const chunkName = `chunk-${name}-${chunk}`
      await uploadService.storeChunkInfo(files.filepath, chunkName)
      ctx.body = {
        message: '分片上传成功！',
        status: true
        // data: { chunkPath }
      }
    } catch (error) {
      // console.error('上传分片出错:', error)
      ctx.status = 400
      ctx.body = { status: false, message: '上传分片出错' }
    }
  },
  // async combine(ctx) {
  //   const { name, chunks } = ctx.request.body

  //   if (!name || !chunks) {
  //     ctx.status = 400
  //     ctx.body = { status: false, message: '合并参数不正确' }
  //     return
  //   }

  //   try {
  //     const chunksPath = path.resolve(__dirname, '../bigfileUploads/chunks')
  //     const filePath = await uploadService.combineChunks(
  //       chunksPath,
  //       name,
  //       chunks
  //     )
  //     // 获取存储在临时目录中的文件信息
  //     const fileData = {
  //       originalFilename: name,
  //       mimetype: 'bigFile',
  //       path: filePath,
  //       size: -1
  //     }
  //     const savedFile = await uploadService.saveUploadFile(fileData)
  //     ctx.body = {
  //       status: true,
  //       message: '合并分片成功！',
  //       data: savedFile
  //     }
  //   } catch (error) {
  //     console.error('合并分片出错:', error)
  //     ctx.status = 400
  //     ctx.body = { status: false, message: '合并分片出错' }
  //   }
  // },
  // async combineSSE(ctx) {
  //   await uploadService.combineSSE(ctx)
  // },
  async checkExistence(ctx) {
    const name = ctx.query.name
    const isExist = await uploadService.checkExistence(name)
    if (isExist) {
      ctx.status = 400
      ctx.body = {
        status: false,
        message: '文件已存在'
      }
    } else {
      ctx.status = 200
      ctx.body = {
        status: true,
        message: '开始上传分片内容，请勿操作页面！'
      }
    }
  },
  async merge(ctx) {
    const { name, chunks } = ctx.request.body
    const taskId = generateId('merge_', 9)
    console.log(taskId)
    if (!name || !chunks) {
      ctx.status = 400
      ctx.body = { status: false, message: '合并参数不正确' }
      return
    }
    try {
      uploadService.merge(name, chunks, mergeStatus, taskId)
      ctx.status = 200
      ctx.body = {
        status: true,
        message: '合并任务开始！',
        data: taskId
      }
    } catch (err) {
      throw new HttpError(err.message, 400)
    }
  },
  async getMergeProgress(ctx) {
    const { taskId } = ctx.params
    try {
      // 获取合并进度
      const status = mergeStatus.get(taskId) || {
        status: false,
        data: 'pending'
      }
      ctx.status = 200
      ctx.body = {
        status: true,
        message: '查询合并进度成功！',
        data: status
      }
    } catch (err) {
      throw new HttpError(err.message, 400)
    }
  },
  async getBigfiles(ctx) {
    try {
      const data = await uploadService.getBigfiles()
      ctx.status = 200
      ctx.body = {
        status: true,
        message: '查询成功！',
        data: data
      }
    } catch (err) {
      throw new HttpError(err.message, 400)
    }
  }
}
module.exports = uploadController
